﻿using Ls.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ls.Utils
{
    public static partial class CommonHelper
    {
        /// <summary>Zips.</summary>
        ///
        /// <param name="text">The text.</param>
        ///
        /// <returns>A byte[].</returns>
        public static string GZip(this string text)
        {
            var buffer = Encoding.UTF8.GetBytes(text);
            using (var ms = new MemoryStream())
            using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
            {
                zipStream.Write(buffer, 0, buffer.Length);
                zipStream.Close();

                return Encoding.UTF8.GetString( ms.ToArray());
            }
        }

        /// <summary>Unzips the given gz buffer.</summary>
        ///
        /// <param name="gzText">Buffer for gz data.</param>
        ///
        /// <returns>A string.</returns>
        public static string GUnzip(this string gzText)
        {
            var gzBuffer = Encoding.UTF8.GetBytes(gzText);
            using (var compressedStream = new MemoryStream(gzBuffer))
            using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
            {
                StreamReader reader = new StreamReader(zipStream,encoding: Encoding.UTF8);
                string result = reader.ReadToEnd();
                reader.Close();
                return result;
            }
        }
    }
}
